package com.free.mini.gateway.utils.encryption;

import java.util.*;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.free.mini.gateway.config.ApiKeysConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SignatureUtil {

    private static final String secret = "hy0kle#MM/cb";

    /**
     * 签名
     */
    public static String sign(JSONObject jsonObject) {
        return sign(jsonObject,secret);
    }

    /**
     * 签名
     */
    public static String sign(JSONObject jsonObject, String signSecret) {
        // 构造签名串
        StringBuilder build = new StringBuilder();
        if (jsonObject != null) {
            Set<String> keySet = jsonObject.keySet();
            List<String> keys = new ArrayList<>(keySet);
            Collections.sort(keys);

            for (int i = 0; i < keys.size(); i++) {
                String key = keys.get(i);
                if ("signature".equals(key)) {
                    continue;
                }
                String v = jsonObject.getString(key);
                build.append(key).append("=").append(v).append("&");
                jsonObject.put(key, v);
            }
        }
        build.append(signSecret);
        log.debug(build.toString());
        return MD5UtilsCash.getMD5(build.toString());
    }

    public static String checkSign(String data, boolean needUrlEncoder, ApiKeysConfig apiKeysConfig) {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        try {
            String signSecret = apiKeysConfig.getSignSecret();
            String decryptStr = AES.decryptAES(data, needUrlEncoder, apiKeysConfig);
            TreeMap treeMap = JSONObject.parseObject(decryptStr, TreeMap.class);
            String signature = treeMap.get("signature") + "";
            String json = JSON.toJSONString(treeMap);
            String sign = sign(JSON.parseObject(json), signSecret);
            if (signature.equals(sign)) {
                return json;
            }
        } catch (Exception e) {
            log.error("api解密失败", e.getMessage(), data);
        }
        return null;
    }

    public static void main(String[] args) {
        // String data =
        // "{\"mobile\":\"8888880006\",\"sms_type\":\"7\",\"app_version\":\"1.0.0\",\"platform\":\"sdk\",\"os\":\"android
        // 8.1.0\",\"imei\":\"45645645564565\",\"model\":\"Android SDK built for
        // x86\",\"brand\":\"google\",\"longitude\":\"\",\"latitude\":\"\",\"city\":\"\",\"time_zone\":\"GMT\",\"network\":\"4G\",\"is_simulator\":\"0\",\"noise\":\"D3Sl8BaVmgUMIK04xp\",\"request_time\":\"1576737606051\",\"access_token\":\"\"}";
        // String data1 =
        // "access_token=&app_version=1.0.0&auth_code=1111&brand=google&city=&imei=45645645564565&is_simulator=0&latitude=&longitude=&mobile=8888888003&model=Android
        // SDK built for x86&network=4G&noise=D3Sl8BaVmgUMIK04xp&os=android
        // 8.1.0&platform=sdk&request_time=1576734385725&time_zone=GMT&hy0kle#MM/cb";
        //
        // String data = "{\"userId\":191231010000009905}";
        String data =
            "{\"userId\": 191231010000009920,\"merchantId\": \"1\",\"thirdOrderId\": \"123\",\"orderAmount\": \"10\",\"transType\": 1,\"mobile\": \"13121984213\",\"goodsName\": \"name\",\"goodsDetails\": \"goodsDetail\",\"installmentId\": 1,\"couponId\": 1,\"channelId\": 1}";
        JSONObject map = JSON.parseObject(data);
        // String signature =
        // "SZ+3felhSYHK5Mp/W4PRIJ2EQdzHY6cWIdUoHyT9QXCD+VUJiCUS9ryHv4uu+XYjwczq94PEGc6selXC7kPSgTWEs6DSe4x9iYE4s4tbcYwUCsB39n/efOQjJQJZX3RqRWktR5b35KJnezMDRLY0CqfF1bScvOizz6iwPmHT+RDdyA4ajC+9MHK3q/WKwOZlRK5Fit/WwnY2Bun9qrOZ29x7wNNtFsNkUbuqjXnVxN3ZHgVtORzGf1VrNf6IbqtV0kFi3xEthVJCpB7Na+I/ZbeTu3Xc5lH1OJqsU7lxO1hH/UMTxTGYFJ3Wu92lWfcEuAa7l+Vr2xxSTe7gD+YoeLW/lknNk/kVpwcR0AwfTLgula9ekmrrCJ7gYRNJv5FZFWOcH03a0Tjz5KWrVbrUFR08sVDFf8MM0c1SI8CnophBgNQzdabaLz9HvxgqyE+7HVftb73q06KTCqoAwo3LaJ/Dk/rbL66eBvhgQH1kG+uzd+ZeFO9srXjDdfyfZfr61Lqq0TaRrmTpGV3AElg3Sg==";
        // log.debug(data1);
        String signature = sign(map);

        // log.debug(signature);
        log.debug(signature);

        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6m78IhxltZZsVgfjXHzvkqLELKgJHLJBl%2BB%2FYY36j3U9FyOO5fN%2BuxbErlAHd4QRI%2F73iaxjI0bysLtk64GzE2D%2FCFCVuPmQg1u7JUANX%2FcLR5CDXcnItn5VBNGI";
        log.debug("param:{}", AES.decryptAES(param, true, new ApiKeysConfig()));
    }
}
